package com.javasm.sys.impl;

import cn.hutool.core.util.StrUtil;
import com.javasm.sys.MenuService;
import com.javasm.sys.RoleService;
import com.javasm.sys.SysMenu;
import com.javasm.sys.SysRole;
import com.javasm.sys.dao.RoleDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleDao roleDao;
    @Resource
    private MenuService menuService;

    @Override
    public List<SysRole> getAllRoles() {
        return roleDao.getAllRoles();
    }

    @Override
    public List<SysRole> getRoles(SysRole role) {
        return roleDao.getRoles(role);
    }

    @Override
    public Integer updateRoleById(SysRole role) {
//        首先删除和该roleid相关的中间表记录
//        删除完成后新增中间表记录
//        更新菜单数据
        roleDao.delMenuRole(role.getRoleId());
        if(role.getAuthStr() != null && role.getAuthStr().length() != 0) {
            String[] split = role.getAuthStr().split(",");
            for (int i = 0; i < split.length; i++) {
                roleDao.insertAuth(role.getRoleId(), split[i]);
            }
        }
        return roleDao.updateRoleById(role);
    }

    @Override
    public Integer insertRoleAndAuth(SysRole role) {
       Integer insert = roleDao.insertRole(role);
        Integer roleId = role.getRoleId();
        String[] split = role.getAuthStr().split(",");
        for (int i = 0; i < split.length; i++) {
            roleDao.insertAuth(roleId, split[i]);
        }
        return insert;
    }

    @Override
    public List<Integer> getMenuId(String roleId) {
        List<Integer> menuIds = roleDao.getMenuList(roleId);
        List<Integer> res = new ArrayList<>();
        for (Integer menuId : menuIds) {
            List<SysMenu> menuByPidList = roleDao.getMenuByPid(menuId);
            if(menuByPidList.size() == 0) {
                res.add(menuId);
            }
        }
        return res;
    }

    @Override
    public Integer delRoleByIds(List<String> ids) {
//        删除和该角色相关联中间表记录
        for (String id : ids) {
            roleDao.delMenuRole(Integer.parseInt(id));
        }
        return roleDao.delRoleByIds(ids);
    }

    @Override
    public List<String> getMenuPermits(String roleId) {
        List<Integer> menuIds = roleDao.getMenuList(roleId);
        List<SysMenu> menus = menuService.getMenusbyIds(menuIds);
        return menus.stream().filter(a-> StrUtil.isNotEmpty(a.getMenuPermit())).map(SysMenu::getMenuPermit).collect(Collectors.toList());
    }
}
